package com.hmdp;

import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstants;
import com.hmdp.entity.Shop;
import com.hmdp.service.IShopService;
import com.hmdp.service.impl.ShopServiceImpl;
import com.hmdp.utils.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * ApplicationInit
 * </p>
 *
 * @author flyduck
 * @since 2025/3/10
 */
@SpringBootTest
public class ApplicationInit {

    @Resource
    private ShopServiceImpl shopService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void saveShop2Redis(){
        shopService.saveShop2Redis(1L,10);
    }

    @Test
    public void saveAllShopGeo2Redis(){
        //1、查询店铺信息
        List<Shop> shopList = shopService.list();

        //2、将店铺信息按照typeId分组
        Map<Long,List<Shop>> map = shopList.stream()
                .collect(Collectors.groupingBy(Shop::getTypeId));

        //3、typeId一样的保存到一个zset集合里面
        for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
            Long typeId = entry.getKey();
            List<Shop> shops = entry.getValue();
            //geoadd key 经度 维度 member
//            for (Shop shop : shops) {
//                stringRedisTemplate.opsForGeo().add(
//                        RedisConstants.RedisShopConstants.SHOP_GEO_PREFIX + typeId.toString(),
//                        new Point(shop.getX(), shop.getY()),
//                        shop.getId().toString());
//            }

            List<RedisGeoCommands.GeoLocation<String>> locations = new ArrayList<>();
            for (Shop shop : shops) {
                RedisGeoCommands.GeoLocation<String> geoLocation = new RedisGeoCommands.GeoLocation<>(shop.getId().toString(),new Point(shop.getX(), shop.getY()));
                locations.add(geoLocation);
            }
            stringRedisTemplate.opsForGeo().add(RedisConstants.RedisShopConstants.SHOP_GEO_PREFIX + typeId.toString(), locations);
        }
    }

}
